//save,get
const express = require('express');
const router = express.Router();
const passport = require("passport");
const mongoose = require('mongoose');
const Coll = require('../../models/Collection');
const Post = require('../../models/Post');


//$route  Post api/colls/doColl
//@desc   return state
//@access private
router.post("/doColl", passport.authenticate("jwt", {
    session: false
}), (req, res) => {
    let option = {
        user: req.user.id,
        post: req.body.post,
    };
    isExist(option, doc => {
        //如果不存在这个用户对这条博客的收藏记录就存一条
        if (doc.length == 0) {
            let coll = new Coll(option);
            coll.save((err) => {
                if (err) {
                    res.json({
                        "ok": 1
                    });
                } else {
                    res.json({
                        "ok": 0
                    });
                }
            })
        } else {
            //如果存在这个用户对这条博客的收藏记录就删除
            Coll.deleteOne(option, err => {
                if (err) {
                    res.json({
                        "ok": 1
                    });
                } else {
                    res.json({
                        "ok": 2
                    });
                }
            })
        }
    })
})

//$route  Post api/colls/getColls
//@desc   return postId
//@access private
//用户收藏的post
router.post('/getColls', passport.authenticate("jwt", {
    session: false
}), (req, res) => {
    Coll.find({
            'user': req.user.id
        }, {
            '_id': 0,
            'post': 1
        })
        .then((docs) => {

            res.json({
                'ok': 0,
                'data': docs
            });

        })
})

//获得某个用户的所有收藏
router.post('/getUserColls', passport.authenticate("jwt", {session: false}), (req, res) => {
    
    Coll.find({'user': req.user.id}, {'post': 1,'_id': 0})
        .then(posts => {
            if (posts.length == 0) {
                res.json({
                    'ok': 0,
                    'data': []
                });
            } else {
                    let postsId=[];
                    for(let i=0;i<posts.length;i++){
                        postsId.push(mongoose.Types.ObjectId(posts[i].post))
                    }
                    Post 
                    .aggregate([
                        {
                            $match:{'_id':{
                                $in:postsId
                            }}
                        },
                        {
                            $lookup: {
                                from: 'users',
                                localField: 'author',
                                foreignField: '_id',
                                as: 'author',
                            }
                        },
                        {
                            $lookup: {
                                from: 'comments',
                                localField: '_id',
                                foreignField: 'post',
                                as: 'comments',
                            }
                        },
                        {
                            $lookup: {
                                from: 'greats',
                                localField: '_id',
                                foreignField: 'post',
                                as: 'greats',
                            }
                        },
                        {
                            $lookup: {
                                from: 'reads',
                                localField: '_id',
                                foreignField: 'post',
                                as: 'reads',
                            }
                        },
                        {
                            $unwind: '$author',
                        },
                        {
                            $limit: 10,
                        },
                        {
                            $sort: {
                                'comments': -1
                            },
                        },
                        {
                            $project: {
                                title: 1,
                                content: '$content',
                                postDate: '$postDate',
                                author: {
                                    '_id': '$author._id',
                                    'name': '$author.name',
                                    'avatar': '$author.avatar'
                                },
                                commentsCount: '$comments._id',
                                greatsCount: '$greats._id',
                                readsCount: '$reads._id',
                            }
                        }
                    ])
                    .exec((err, posts) => {
                        if (err) {
                            console.log(err)
                            res.json({
                                'ok': 1,
                                'data': []
                            });
                        } else {
                            // getPostUser(posts,(users)=>{
                            // console.log(posts);
                            for (let i = 0; i < posts.length; i++) {
                                posts[i].commentsCount = posts[i].commentsCount.length;
                                posts[i].greatsCount = posts[i].greatsCount.length;
                                posts[i].readsCount = posts[i].readsCount.length;
                            }
                            res.json({
                                'ok': 0,
                                'data': posts
                            });
                            // })
                        }
                    })
            }
        })
})

function isExist(option, callback) {
    let {
        user,
        post
    } = option;
    Coll.find({
            user: user,
            post: post
        })
        .then((doc) => {
            callback(doc);
        })
        .catch(err => {
            console.log(err);
        })
}

module.exports = router;